//#region AutoCreateCode
import {
  hideObjectKeysWithoutValues,
  hideSelectedObjectKeys,
  processIdValue,
  processIdArray,
} from '../../helpers/utilsJS';
import { deleteFromCache, setExCache } from '../../helpers/redis';
import log from "../../helpers/logger";
import { RequestParserService } from '../../lib/request-parser/src';
import { generateRowLevelPermissionFilter, checkUserHasPermission, getUserAuthorizedDataIds } from '../../helpers/permissionUtils';
import { PERMISSION_LEVEL } from '../../middlewares/auth/rowLevelPermission';
import { PrismaClient } from '../../../../prisma/generated/uctoo'

const db = new PrismaClient({
  log: ['query', 'info', 'warn', 'error'],
});

// 定义当前表的ID字段类型
const ID_FIELD_TYPE = 'uuid';

export async function createMinishopProductCategory(minishopProductCategory) {
  try {
    minishopProductCategory = hideSelectedObjectKeys(minishopProductCategory, ['id']);
    const newMinishopProductCategory = await db.minishop_product_category.create({
      data: {
        ...minishopProductCategory
      },
    });
    //Cache after create
    // setExCache(newMinishopProductCategory.id, 3600, JSON.stringify(newMinishopProductCategory));
    return newMinishopProductCategory;
  } catch (e) {
    log.error(e);
    return false;
  }
}

export async function editMinishopProductCategoryInDatabase(updatedMinishopProductCategory, minishopProductCategoryId, userId?) {
  try {
    const isEnabled = process.env.ROW_LEVEL_PERMISSION_ENABLED === 'true';
    
    // 如果启用了行级权限且提供了userId，检查是否有写权限
    if (isEnabled && userId) {
      const permissionResult = await checkUserHasPermission(userId, 'minishop_product_category', minishopProductCategoryId, PERMISSION_LEVEL.WRITE);
      if (!permissionResult.hasPermission) {
        log.warn(`User ${userId} has no permission to edit minishop_product_category ${minishopProductCategoryId}: ${permissionResult.reason}`);
        return { success: false, reason: permissionResult.reason };
      }
    }
    
    updatedMinishopProductCategory = hideSelectedObjectKeys(updatedMinishopProductCategory, ['id']);
    updatedMinishopProductCategory = hideObjectKeysWithoutValues(updatedMinishopProductCategory);
    updatedMinishopProductCategory.updated_at = new Date().toISOString(); 
    if(updatedMinishopProductCategory.deleted_at === "0"){  //recycle data
      const minishopProductCategoryFromDb = await db.minishop_product_category.update({
        data: { deleted_at: { set: null } },
        where: {
          id: processIdValue(minishopProductCategoryId, ID_FIELD_TYPE),
        },
      });
      //Cache after edit
      // setExCache(minishopProductCategoryFromDb.id, 3600, JSON.stringify(minishopProductCategoryFromDb));
      if (!minishopProductCategoryFromDb) return { success: false, reason: '实体不存在' };
      return { success: true, data: minishopProductCategoryFromDb };
    }else{
      
      const minishopProductCategoryFromDb = await db.minishop_product_category.update({
        data: updatedMinishopProductCategory,
        where: {
          id: processIdValue(minishopProductCategoryId, ID_FIELD_TYPE),
        },
      });
      //Cache after edit
      // setExCache(minishopProductCategoryFromDb.id, 3600, JSON.stringify(minishopProductCategoryFromDb));
      if (!minishopProductCategoryFromDb) return { success: false, reason: '实体不存在' };
      return { success: true, data: minishopProductCategoryFromDb };
    }
    
  } catch (e) {
    log.error(e);
    return { success: false, reason: '编辑实体时发生错误' };
  }
}

export async function editMultiMinishopProductCategoryInDatabase(updatedMinishopProductCategory, ids, userId?) {
  try {
    const isEnabled = process.env.ROW_LEVEL_PERMISSION_ENABLED === 'true';
    
    // 如果启用了行级权限且提供了userId，检查是否对每个实体都有写权限
    if (isEnabled && userId) {
      for (const minishopProductCategoryId of ids) {
        const permissionResult = await checkUserHasPermission(userId, 'minishop_product_category', minishopProductCategoryId, PERMISSION_LEVEL.WRITE);
        if (!permissionResult.hasPermission) {
          log.warn(`User ${userId} has no permission to edit minishop_product_category ${minishopProductCategoryId}: ${permissionResult.reason}`);
          return { success: false, reason: permissionResult.reason, minishopProductCategoryId: minishopProductCategoryId };
        }
      }
    }
    
    updatedMinishopProductCategory = hideSelectedObjectKeys(updatedMinishopProductCategory, ['id','ids']);
    updatedMinishopProductCategory = hideObjectKeysWithoutValues(updatedMinishopProductCategory);
    updatedMinishopProductCategory.updated_at = new Date().toISOString(); 
    if(updatedMinishopProductCategory.deleted_at === "0"){  //recycle data
      const minishopProductCategoryFromDb = await db.minishop_product_category.updateMany({
        data: { deleted_at: { set: null } },
        where: {
          id: {in: processIdArray(ids, ID_FIELD_TYPE)},
        },
      });
      if (!minishopProductCategoryFromDb) return { success: false, reason: '未找到要恢复的实体' };
      return { success: true, data: minishopProductCategoryFromDb };
    }else{
      const minishopProductCategoryFromDb = await db.minishop_product_category.updateMany({
        data: updatedMinishopProductCategory,
        where: {
          id: {in: processIdArray(ids, ID_FIELD_TYPE)},
        },
      });
      if (!minishopProductCategoryFromDb) return { success: false, reason: '未找到要编辑的实体' };
      return { success: true, data: minishopProductCategoryFromDb };
    }
    
  } catch (e) {
    log.error(e);
    return { success: false, reason: '批量编辑实体时发生错误' };
  }
}

export async function deleteMinishopProductCategoryFromDatabase(minishopProductCategoryId,force = 0, userId?) {
  try {
    const isEnabled = process.env.ROW_LEVEL_PERMISSION_ENABLED === 'true';
    
    // 如果启用了行级权限且提供了userId，检查是否有写权限
    if (isEnabled && userId) {
      const permissionResult = await checkUserHasPermission(userId, 'minishop_product_category', minishopProductCategoryId, PERMISSION_LEVEL.WRITE);
      if (!permissionResult.hasPermission) {
        log.warn(`User ${userId} has no permission to delete minishop_product_category ${minishopProductCategoryId}: ${permissionResult.reason}`);
        return { success: false, reason: permissionResult.reason };
      }
    }
    
    if(force){  //real delete data
      await db.minishop_product_category.delete({
        where: {
          id: processIdValue(minishopProductCategoryId, ID_FIELD_TYPE),
        },
      });
    }else{  //soft delete
      await db.minishop_product_category.update({
        data: {deleted_at: new Date().toISOString()},
        where: {
          id: processIdValue(minishopProductCategoryId, ID_FIELD_TYPE),
        },
      });
    }
    // deleteFromCache(minishopProductCategoryId);
    return { success: true };
  } catch (e) {
    log.error(e);
    return { success: false, reason: '删除实体时发生错误' };
  }
}

export async function deleteMultiMinishopProductCategoryFromDatabase(ids,force = 0, userId?) {
  try {
    const isEnabled = process.env.ROW_LEVEL_PERMISSION_ENABLED === 'true';
    
    // 如果启用了行级权限且提供了userId，检查是否对每个实体都有写权限
    if (isEnabled && userId) {
      for (const minishopProductCategoryId of ids) {
        const permissionResult = await checkUserHasPermission(userId, 'minishop_product_category', minishopProductCategoryId, PERMISSION_LEVEL.WRITE);
        if (!permissionResult.hasPermission) {
          log.warn(`User ${userId} has no permission to delete minishop_product_category ${minishopProductCategoryId}: ${permissionResult.reason}`);
          return { success: false, reason: permissionResult.reason, minishopProductCategoryId: minishopProductCategoryId };
        }
      }
    }
    
    if(force){  //real delete multi data
      await db.minishop_product_category.deleteMany({
        where: {
          id:{in: processIdArray(ids, ID_FIELD_TYPE)},
        },
      });
    }else{  //soft delete
      await db.minishop_product_category.updateMany({
        data: {deleted_at: new Date().toISOString()},
        where: {
          id: {in: processIdArray(ids, ID_FIELD_TYPE)},
        },
      });
    }
    // deleteFromCache(minishopProductCategoryId);
    return { success: true };
  } catch (e) {
    log.error(e);
    return { success: false, reason: '批量删除实体时发生错误' };
  }
}

export async function getMinishopProductCategoryFromDatabase(minishopProductCategoryId, userId?) {
  try {
    const isEnabled = process.env.ROW_LEVEL_PERMISSION_ENABLED === 'true';
    
    // 首先检查实体是否存在
    const minishopProductCategoryFromDb = await db.minishop_product_category.findFirst({
      where: {
          id: processIdValue(minishopProductCategoryId, ID_FIELD_TYPE),
        },
    });
    
    // 如果实体不存在，直接返回null
    if (!minishopProductCategoryFromDb) return null;
    
    // 如果启用了行级权限且提供了userId，检查权限
    if (isEnabled && userId) {
      const hasPermission = await checkUserHasPermission(userId, 'minishop_product_category', minishopProductCategoryId, PERMISSION_LEVEL.READ);
      if (!hasPermission) {
        // 用户没有权限访问此实体
        return null;
      }
    }
    
    return minishopProductCategoryFromDb;
  } catch (e) {
    log.error(e);
    return false;
  }
}

export async function getMinishopProductCategorysFromDatabase(limit, page, skip, userId?) {
  try {
    const isEnabled = process.env.ROW_LEVEL_PERMISSION_ENABLED === 'true';
    
    // 使用更明确的类型定义，允许OR属性
    const whereCondition: any = {};
    
    // 如果启用了行级权限且提供了userId，添加权限过滤
    if (isEnabled && userId) {
      // 获取用户有权访问的实体ID列表
      const authorizedIds = await getUserAuthorizedDataIds(userId, 'minishop_product_category', PERMISSION_LEVEL.READ);
      
      // 组合条件：用户创建的实体 或 用户被授权访问的实体
      whereCondition.OR = [
        { creator: userId },
        { id: { in: authorizedIds } }
      ];
    }
    
    const minishopProductCategorysFromDb = await db.minishop_product_category.findMany({
      skip: limit * page + skip,
      take: limit,
      where: whereCondition
    });
    if (!minishopProductCategorysFromDb) return null;
    return minishopProductCategorysFromDb;
  } catch (e) {
    log.error(e);
    return false;
  }
}

export async function queryMinishopProductCategorysFromDatabase(limit, page, skip, query, userId?) {
  try {
    const requestParserService = new RequestParserService();
    const parsedQuery = requestParserService.parseQuery(query);
    // 使用any类型允许动态添加OR和AND属性
    const filter: any = parsedQuery.filter || {};
    
    const isEnabled = process.env.ROW_LEVEL_PERMISSION_ENABLED === 'true';
    
    // 如果启用了行级权限且提供了userId，添加权限过滤
    if (isEnabled && userId) {
      // 获取用户有权访问的实体ID列表
      const authorizedIds = await getUserAuthorizedDataIds(userId, 'minishop_product_category', PERMISSION_LEVEL.READ);
      
      // 组合条件：原始查询条件 + (用户创建的实体 或 用户被授权访问的实体)
      const originalWhere = { ...filter };
      
      // 组合条件：用户创建的实体 或 用户被授权访问的实体
      filter.OR = [
        { creator: userId },
        { id: { in: authorizedIds } }
      ];
      
      // 如果原始查询条件不为空，将其合并到每个OR条件中
      if (Object.keys(originalWhere).length > 0) {
        filter.AND = [originalWhere];
      }
    }
    
    const minishopProductCategorysFromDb = await db.minishop_product_category.findMany({
      skip: limit * page + skip,
      take: limit,
      where: filter,
      orderBy: parsedQuery.sort,
    });
    if (!minishopProductCategorysFromDb) return null;
    return minishopProductCategorysFromDb;
  } catch (e) {
    log.error(e);
    return false;
  }
}

export async function countMinishopProductCategorys(userId?) {
  try {
    const isEnabled = process.env.ROW_LEVEL_PERMISSION_ENABLED === 'true';
    
    let totalCount = 0;
    
    // 如果启用了行级权限且提供了userId，使用不同的方式处理权限过滤
    if (isEnabled && userId) {
      // 获取用户有权访问的实体ID列表
      const authorizedIds = await getUserAuthorizedDataIds(userId, 'minishop_product_category', PERMISSION_LEVEL.READ);
      
      // 直接在初始化时定义OR属性，避免类型错误
      const whereCondition = {
        OR: [
          { creator: userId },
          { id: { in: authorizedIds } }
        ]
      };
      
      // 计算符合条件的实体数量
      totalCount = await db.minishop_product_category.count({
        where: whereCondition
      });
    } else {
      // 不启用行级权限时，直接计算所有实体数量
      totalCount = await db.minishop_product_category.count();
    }
    
    return totalCount;
  } catch (e) {
    log.error(e);
    return false;
  }
}
//#endregion AutoCreateCode